let healthChart;   
let diabetesChart;  
let radarChart;   

const ctx = document.getElementById('healthChart').getContext('2d');  
const diabetesCtx = document.getElementById('diabetesChart').getContext('2d');  
const radarCtx = document.getElementById('radarChart').getContext('2d');  

let currentPage = 1; // 当前页  
let totalRecords = 0; // 总记录数  
const recordsPerPage = 10; // 每页显示的记录数  

// 页面加载时获取记录和统计数据  
window.onload = async () => {  
    await fetchAllRecords();  
    await fetchDiabetesStats();  
    await fetchDiabetesMeans();  
};  

function fetchRecords() {  
    const date = document.getElementById('date-picker').value;  
    const url = `/history_data?date=${date}&page=${currentPage}`; // 传递键值对附加信息  
    fetch(url)  
        .then(response => response.json())  
        .then(data => {  
            updateHistoryTable(data.records);  
            totalRecords = data.total_records; // 储存总记录数  
            updatePagination(); // 更新翻页信息  
            prepareChartData(data.records); // 准备图表数据  
        });  
}  

function updateChart() {  
    fetchRecords(); // 重新获取记录以更新图表  
} 

function fetchAllRecords() {  
    const url = `/history_data?page=${currentPage}`; // 直接传递当前页码  
    fetch(url)  
        .then(response => response.json())  
        .then(data => {  
            updateHistoryTable(data.records);  
            totalRecords = data.total_records; // 储存总记录数  
            updatePagination(); // 更新翻页信息  
            prepareChartData(data.records); // 准备图表数据  
        });  
}  

function fetchPatientRecords() {  
    const patientId = document.getElementById('patient-id').value; // 获取患者ID  
    const url = `/patient_data?patient_id=${patientId}`; // 发送请求获取患者记录  
    fetch(url)  
        .then(response => response.json())  
        .then(data => {  
            updateHistoryTable(data.records);  
            totalRecords = data.records.length; // 更新总记录数为返回的记录数  
            updatePagination(); // 更新翻页信息  
            prepareChartData(data.records); // 准备图表数据  
        });  
}  

function changePage(direction) {  
    currentPage += direction;  
    fetchAllRecords(); // 重新获取记录  
}  

function updatePagination() {  
    document.getElementById('current-page').innerText = `第 ${currentPage} 页`;  
    document.getElementById('prev-page').disabled = currentPage === 1; // 如果在第一页则禁用上一页按钮  
    document.getElementById('next-page').disabled = currentPage * recordsPerPage >= totalRecords; // 如果达到了最后一页则禁用下一页按钮  
}  

function updateHistoryTable(records) {  
    const tableBody = document.querySelector("#history-table tbody");  
    tableBody.innerHTML = "";  //清空

    // 遍历每一个记录（record）对象来生成表格行
    records.forEach(record => {  
        const row = document.createElement("tr");  
        row.innerHTML = `  
            <td>${record[1]}</td>  
            <td>${record[2]}</td>  
            <td>${record[3]}</td>  
            <td>${record[4]}</td>  
            <td>${record[5]}</td>  
            <td>${record[6]}</td>  
            <td>${record[7]}</td>  
            <td>${record[8]}</td>  
            <td>${record[9]}</td>   
            <td>${record[10]}</td>  
            <td>${record[11] == 1 ? '糖尿病' : '正常'}</td>   
        `;  
        tableBody.appendChild(row);  
    });  
}  

function prepareChartData(records) {  
    const labels = records.map(record => record[1]); //病人ID  
    const pregnanciesData = records.map(record => record[3]); // 怀孕次数  
    const bloodSugarData = records.map(record => record[4]); // 血糖  
    const bloodPressureData = records.map(record => record[5]); //血压  
    const skinThicknessData = records.map(record => record[6]); // 皮肤厚度  
    const insulinData = records.map(record => record[7]); // 胰岛素  
    const bmiData = records.map(record => record[8]); // BMI  
    const ageData = records.map(record => record[9]); //年龄  
    const diagnosisData = records.map(record => record[10]); //糖尿病谱系功能  

    const datasets = [];  
    //  加个复选框，让用户选择要显示的图表数据  
    if (document.getElementById('show-pregnancies').checked) {  
        datasets.push({  
            label: '怀孕次数',  
            data: pregnanciesData,  
            borderColor: 'rgba(75, 192, 192, 1)',  
            borderWidth: 2,  
            fill: false,  
        });  
    }  

    if (document.getElementById('show-blood-sugar').checked) {  
        datasets.push({  
            label: '血糖',  
            data: bloodSugarData,  
            borderColor: 'rgba(255, 99, 132, 1)',  
            borderWidth: 2,  
            fill: false,  
        });  
    }  

    if (document.getElementById('show-blood-pressure').checked) {  
        datasets.push({  
            label: '血压',  
            data: bloodPressureData,  
            borderColor: 'rgba(54, 162, 235, 1)',  
            borderWidth: 2,  
            fill: false,  
        });  
    }  

    if (document.getElementById('show-skin-thickness').checked) {  
        datasets.push({  
            label: '皮肤厚度',  
            data: skinThicknessData,  
            borderColor: 'rgba(255, 206, 86, 1)',  
            borderWidth: 2,  
            fill: false,  
        });  
    }  

    if (document.getElementById('show-insulin').checked) {  
        datasets.push({  
            label: '胰岛素',  
            data: insulinData,  
            borderColor: 'rgba(153, 102, 255, 1)',  
            borderWidth: 2,  
            fill: false,  
        });  
    }  

    if (document.getElementById('show-bmi').checked) {  
        datasets.push({  
            label: 'BMI',  
            data: bmiData,  
            borderColor: 'rgba(255, 159, 64, 1)',  
            borderWidth: 2,  
            fill: false,  
        });  
    }  

    if (document.getElementById('show-age').checked) {  
        datasets.push({  
            label: '年龄',  
            data: ageData,  
            borderColor: 'rgba(75, 192, 192, 1)',  
            borderWidth: 2,  
            fill: false,  
        });  
    }  

    if (document.getElementById('show-diagnosis').checked) {  
        datasets.push({  
            label: '糖尿病谱系功能',  
            data: diagnosisData,  
            borderColor: 'rgba(255, 99, 132, 1)',  
            borderWidth: 2,  
            fill: false,  
        });  
    }  

    // 初始化图表  
    if (healthChart) {  
        healthChart.destroy(); // 销毁已存在的图表  
    }  
    healthChart = new Chart(ctx, {  
        type: 'line',  
        data: {  
            labels: labels,  
            datasets: datasets,  
        },  
        options: {  
            responsive: true,  
            scales: {  
                y: {  
                    title: {  
                        display: true,  
                        text: '数值'  
                    },  
                },  
            },  
            plugins: {  
                legend: {  
                    display: true,  
                    position: 'top',  
                },  
            },  
        },  
    });  
}  

async function fetchDiabetesStats() {  
    const response = await fetch('/diabetes_stats');  
    const data = await response.json();  

    // 初始化更新糖尿病统计图表  
    if (diabetesChart) {  
        diabetesChart.destroy(); 
    }  
    diabetesChart = new Chart(diabetesCtx, {  
        type: 'pie',  
        data: {  
            labels: ['糖尿病患者', '正常患者'],  
            datasets: [{  
                data: [data.diabetic, data.normal],  
                backgroundColor: ['rgba(255, 99, 132, 0.6)', 'rgba(54, 162, 235, 0.6)'],  
                borderColor: ['rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)'],  
                borderWidth: 1  
            }]  
        },  
        options: {  
            responsive: true,  
            plugins: {  
                legend: {  
                    display: true,  
                    position: 'top',  
                },  
                title: {  
                    display: true,  
                    text: '糖尿病患者与正常患者统计',  
                }  
            }  
        }  
    });  
}  

async function fetchDiabetesMeans() {  
    const response = await fetch('/diabetes_means');  
    const data = await response.json();  

    // 初始化或更新雷达图  
    if (radarChart) {  
        radarChart.destroy(); // 销毁已存在的雷达图  
    }  

    const labels = ['怀孕次数', '血糖', '血压', '皮肤厚度', '胰岛素', 'BMI', '年龄'];  
    const normalData = data.normal.map(mean => mean.toFixed(2)); // 格式化两位数的均值  
    const diabeticData = data.diabetic.map(mean => mean.toFixed(2));  

    radarChart = new Chart(radarCtx, {  
        type: 'radar',  
        data: {  
            labels: labels,  
            datasets: [  
                {  
                    label: '正常患者',  
                    data: normalData,  
                    backgroundColor: 'rgba(54, 162, 235, 0.6)',  
                    borderColor: 'rgba(54, 162, 235, 1)',  
                    borderWidth: 1  
                },  
                {  
                    label: '糖尿病患者',  
                    data: diabeticData,  
                    backgroundColor: 'rgba(255, 99, 132, 0.6)',  
                    borderColor: 'rgba(255, 99, 132, 1)',  
                    borderWidth: 1  
                }  
            ]  
        },  
        options: {  
            responsive: true,  
            scales: {  
                r: {  
                    beginAtZero: true  
                }  
            },  
            plugins: {  
                legend: {  
                    display: true,  
                    position: 'top',  
                },  
                title: {  
                    display: true,  
                    text: '正常患者与糖尿病患者各项指标均值'  
                }  
            }  
        }  
    });  
}

document.addEventListener('DOMContentLoaded', function () {  
    fetchAndPlotBoxPlots();  
});  

async function fetchAndPlotBoxPlots() {  
    try {  
        const response = await fetch('/api/xxdata');    
        const data = await response.json();   
        const features = ['pregnancies', 'glucose', 'bloodpressure', 'skinthickness', 'insulin', 'bmi', 'dpf', 'age'];  

        const diabeticData = features.map(feature => {  
            return data.filter(record => record.prediction === 1).map(record => record[feature]);  
        });  

        const nonDiabeticData = features.map(feature => {  
            return data.filter(record => record.prediction === 0).map(record => record[feature]);  
        });  

        const diabeticTraces = features.map((feature, i) => ({  
            y: diabeticData[i],  
            type: 'box',  
            name: feature  
        }));  

        const nonDiabeticTraces = features.map((feature, i) => ({  
            y: nonDiabeticData[i],  
            type: 'box',  
            name: feature  
        }));  
 
        Plotly.newPlot('diabetic-boxplot', diabeticTraces, {  
            title: '糖尿病患者箱线图',  
            boxmode: 'group'  
        }, {displayModeBar: false});  

        Plotly.newPlot('non-diabetic-boxplot', nonDiabeticTraces, {  
            title: '正常患者箱线图',  
            boxmode: 'group'  
        }, {displayModeBar: false});  
        
    } catch (error) {  
        console.error('Error fetching or plotting box plot data:', error);  
    }  
}

